<template>
  <div class="content-wrapper">
    <div class="content-container">
      <el-form
        ref="dataForm"
        :model="temp"
        label-position="right"
        label-width="120px"
      >
        <el-row>
          <el-col :span="24" style="margin-bottom: 20px">
            <el-button
              v-if="isView && currentStatus"
              size="mini"
              type="primary"
              round
              :disabled="confirmLoading"
              :loading="tempSaveLoading"
              @click="handleTempReCheckReceive()"
            >
              确认复核
            </el-button>
            <el-button
              v-if="isView && !currentStatus"
              type="primary"
              size="mini"
              round
              :disabled="tempSaveLoading"
              :loading="confirmLoading"
              @click="handleConfirmReceive()"
            >
              完成记录
            </el-button>
            <el-button
              v-if="isView && !currentStatus"
              style="margin: 0px 10px"
              size="mini"
              round
              @click.stop="handleOpenAddEquipment()"
            >
              添加设备
            </el-button>
            <el-select
              v-if="isView && !currentStatus"
              v-model="recordTemplate"
              value-key="recordTemplateId"
              size="mini"
              placeholder="选择记录模板"
              filterable
              :disabled="recordTemplateDisabled || currentStatus"
              @change="handleRecordTemplateChang"
            >
              <el-option
                v-for="item in recordTemplateList"
                :key="item.recordTemplateId"
                :label="item.recordTemplateName"
                :value="item"
              />
            </el-select>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="任务单号">
              <el-select
                v-model="selectedManufactureTask"
                value-key="manufactureTaskId"
                filterable
                @change="handleManufactureTaskChang"
              >
                <el-option
                  v-for="item in manufactureTaskCodeList"
                  :key="item.manufactureTaskId"
                  :label="item.manufactureTaskCode"
                  :value="item"
                >
                  <span style="padding: 2px">
                    <el-tag v-if="item.orderType === 1">分装</el-tag>
                    <el-tag v-else type="success">配制</el-tag>
                    {{
                      item.manufactureTaskCode +
                      '(' +
                      item.manufactureOrderCode +
                      ')'
                    }}
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col v-if="isView" :span="6">
            <el-form-item label="通知单号">
              {{ temp.manufactureOrderCode }}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item v-if="isView" label="类型">
              <span>
                <el-tag v-if="temp.orderType === 1" type="info"> 分装 </el-tag>
                <el-tag v-else type="success">生产</el-tag>
              </span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-collapse v-if="isView" v-model="panels">
          <el-collapse-item name="equipment">
            <template slot="title">
              <span>设备</span>
            </template>
            <EquipmentList
              ref="equipmentList"
              :visible="true"
              :current-task="selectedManufactureTask"
              :equipment-data="equipmentList"
              :current-status="currentStatus"
            />
          </el-collapse-item>
          <el-collapse-item name="goods">
            <template slot="title">
              <span>物料</span>

              <!-- <span v-else>项目</span> -->
            </template>
            <SplitGoodsList
              ref="splitGoodsList"
              :visible="temp.orderType === 1"
              :goods-list="splitGoodeDataList"
              :current-status="currentStatus"
              :current-task="selectedManufactureTask"
            />
            <ManufactureGoodsList
              ref="manufactureGoodsList"
              :visible="temp.orderType === 2"
              :goods-list="splitGoodeDataList"
              :current-status="currentStatus"
              :current-task="selectedManufactureTask"
            />
          </el-collapse-item>
          <el-collapse-item v-if="isView" name="record">
            <template slot="title" slot-scope="{ row }">
              <span style="margin-right: 10px">记录</span>
            </template>
            <RecordList
              ref="recordList"
              :visible="recordDialogVisible"
              :current-type="'manufactureTask'"
              :current-task="selectedManufactureTask"
              :current-row="currentRow"
              :current-status="currentStatus"
              @update-data="updateRecordList"
            />
          </el-collapse-item>
        </el-collapse>
      </el-form>
      <AddEquipment :visible.sync="equipmentDialogVisible" />
      <AddGoods :visible.sync="goodsDialogVisible" />
      <!-- <Record :visible="true" :current-task="currentRow" /> -->
    </div>
  </div>
</template>

<script>
import { formatByKeyValue } from '@/utils'
import {
  listOwnerTaskCode,
  getManufactureTaskData
} from '@/api/mes/manufactureTask.js'

import AddEquipment from './components/AddEquipment'
import AddGoods from './components/AddGoods'
import EquipmentList from './components/EquipmentList'
import SplitGoodsList from './components/SplitGoodsList'
import ManufactureGoodsList from './components/ManufactureGoodsList'
import RecordList from './components/RecordList'

import { getRecordTemplateList } from '@/api/rs/recordTemplate.js'
import { updateTaskLog, saveCheckEquipment } from '@/api/mes/manufactureTask.js'
import { newSort } from '@/utils/common.js'
import { listManufactureTaskRecord } from '@/api/mes/manufactureTask'
import { listRecordTemplateGroupByTemplateId } from '@/api/rs/recordTemplate'
import { saveAllManufactureTaskRecord } from '@/api/mes/manufactureTask'

export default {
  components: {
    AddEquipment,
    AddGoods,
    EquipmentList,
    SplitGoodsList,
    ManufactureGoodsList,
    RecordList
  },
  data() {
    return {
      panels: ['equipment', 'goods', 'record'],
      selectedManufactureTask: null,
      manufactureTaskCodeList: null,
      temp: {
        orderType: 1
      },
      tempSaveLoading: false,
      confirmLoading: false,
      equipmentDialogVisible: false,
      goodsDialogVisible: false,
      recordDialogVisible: false,
      currentRow: null,
      splitGoodeDataList: [],
      recordTemplate: null,
      recordTemplateList: [],
      equipmentList: [],
      goodsList: null,
      recordTemplateDisabled: false,
      tempEquipment: null,
      radio: 3, // temp,
      currentStatus: true,
      isView: false
    }
  },
  watch: {
    splitGoodeDataList(data) {
      data.forEach((e) => {
        if (e.type === 2) {
          if (!e.factQuantity) {
            e.factQuantity = 0
          }
          if (!e.factCount) {
            e.factCount = e.expectCount
          }
        } else {
          if (e.factQuantity) {
            return
          } else {
            if (!e.factQuantity) {
              e.factQuantity = 0
            }
            if (!e.factCount) {
              e.factCount = e.expectCount
            }
          }
        }
      })
    },
    selectedManufactureTask(data) {
      if (data != null) {
        this.isView = true
      } else {
        this.isView = false
      }
    }
  },
  mounted() {
    this.getDataList()
  },

  methods: {
    formatByKeyValue,
    reset() {
      //
    },
    getDataList() {
      listOwnerTaskCode({
        statusList: ['10', '30', '20']
        // status:10
      }).then((res) => {
        this.manufactureTaskCodeList = res.data || []
      })
      getRecordTemplateList({
        pageIndex: 0,
        pageSize: 100,
        scope: 1
      }).then((res) => {
        this.recordTemplateList = res.data
      })
    },
    handleOpenAddEquipment(row) {
      this.$refs.equipmentList.handleOpenAddEquipment()
    },
    handleOpenAddGoods(row) {
      this.goodsDialogVisible = true
    },
    handleOpenRecord(row) {
      this.recordDialogVisible = true
    },
    async handleManufactureTaskChang(row) {
      if (row && row.manufactureTaskId) {
        const data = await getManufactureTaskData({
          manufactureTaskId: row.manufactureTaskId,
          withEquipmentFlag: true,
          withGoodsFlag: true,
          withRecordFlag: true
        })
        this.processingData(data.data)
      }
    },
    processingData(data) {
      this.temp = data
      if (data.status === 10) {
        this.currentStatus = false
      } else {
        this.currentStatus = true
      }
      if (data.goodsList && data.goodsList.length > 0) {
        const goodsList = Array.from(newSort(data.goodsList, 'goodsCode'))
        this.splitGoodeDataList = goodsList
      } else {
        this.splitGoodeDataList = []
      }
      this.equipmentList = data.equipmentList

      const loadIsData = {
        // 返回数据
        recordList: data.recordList,
        recordTemplateGroupList: data.recordTemplateGroupList,
        recordTemplateId: data.recordTemplateId,
        type: 1
      }
      if (data.recordTemplateId) {
        loadIsData.type = 1
        this.recordTemplateDisabled = true
      } else {
        loadIsData.type = 2
        this.recordTemplateDisabled = false
      }
      this.recordTemplate = data.recordTemplateName
      this.recordDialogVisible = true
      this.currentRow = loadIsData
    },
    handleOpenAddRecord() {
      this.recordDialogVisible = true
    },
    handleRecordTemplateChang(val) {
      this.recordDialogVisible = true
      // this.recordTemplateDisabled=true
      // this.currentRow = val
      this.loadTemplate(val).then((res) => {
        const data = res
        this.currentRow = data
      })
      this.$forceUpdate()
    },
    handleConfirmReceive() {
      this.$confirm('此操作将完成该记录计划, 请检查后提交?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          if (
            this.temp.orderType === 1
              ? !this.$refs.splitGoodsList
              : !this.$refs.manufactureGoodsList
          ) {
            this.$message.warning('物料不可为空')
            return
          } else {
            updateTaskLog({
              manufactureTaskId: this.selectedManufactureTask.manufactureTaskId,
              status: 30
            }).then((res) => {
              this.$message.success('保存成功')
              this.selectedManufactureTask = null
              this.equipmentList = []
              this.splitGoodeDataList = []
              this.recordTemplate = ''
              this.currentRow = {}
              this.currentStatus = false
              this.temp = {}
              this.getDataList()
            })
          }
        })
        .catch((err) => {
          console.log(err, 'eeeee')
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    handleTempReCheckReceive() {
      this.$confirm('此操作将完成该记录复核, 请检查后提交?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          saveCheckEquipment({
            manufactureTaskId: this.selectedManufactureTask.manufactureTaskId,
            status: 40
          }).then((res) => {
            this.$message.success('保存成功')
            this.selectedManufactureTask = null
            this.equipmentList = []
            this.splitGoodeDataList = []
            this.recordTemplate = ''
            this.currentRow = []
            this.currentStatus = false
            this.temp = {}
            this.getDataList()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    async loadTemplate(row) {
      let data = []
      let data2 = []
      await listRecordTemplateGroupByTemplateId({
        recordTemplateId: row.recordTemplateId,
        withItem: true
      }).then((response) => {
        data = response.data
      })
      await listManufactureTaskRecord({
        manufactureTaskId: this.selectedManufactureTask.manufactureTaskId
      }).then((response2) => {
        data2 = response2.data
      })
      const currentRow = {
        recordList: data2,
        recordTemplateGroupList: data,
        recordTemplateId: row.recordTemplateId,
        type: row.type
      }
      return currentRow
    },
    ondTemplate() {
      console.log(this.$refs['recordList'], 'this.$refs')
      this.$refs['recordList'].handleCommit()
    },
    updateRecordList(row) {
      saveAllManufactureTaskRecord(row).then((res) => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.content-container {
  overflow: auto;
  height: 98vh;
}
</style>
